"use strict";
const ACTION_SET = {
	GET_MOCKTEST_DATA: "getMockData",
	GET_LAST_HISTORY: 'getLastHistory',
	TEST:'test',
	LAST_CACHE:'setcache'
};
const db = uniCloud.database();
const cmd = db.command
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log("event : ", event);

	let {
		ACTION,
		drive,
		subject
	} = event;
	let result = {};

	console.log('run action', ACTION)
	const AnsOfLable = {
		'A': '0',
		'B': '1',
		'C': '2',
		'D': '3',
		'E': '4',
		'F': '5',
	}

	const labelAns = {
		'0': 'A',
		'1': 'B',
		'2': 'C',
		'3': 'D',
		'4': 'E',
		'5': 'F'
	}
	const shuffle = (arr) => {
		var l = arr.length
		var index, temp
		while (l > 0) {
			index = Math.floor(Math.random() * l)
			temp = arr[l - 1]
			arr[l - 1] = arr[index]
			arr[index] = temp
			l--
		}
		return arr
	}
	const resort = (struct, s_ans) => {

		let arr = []
		let n_ans = [] //重置后的答案
		let s_ans_arr = s_ans.split('|') //重置前答案
		let s_ans_index = []
		for (let s of s_ans_arr) {
			s_ans_index.push(parseInt(AnsOfLable[s]))
		}

		struct.forEach((e, i) => {
			if (s_ans_index.includes(e.index)) {
				arr.push(i)
				n_ans.push(labelAns[`${i}`])
			}
		})
		return {
			realAns: n_ans.join('|'),
			realIndex: arr.join(',')
		}
	}

	const getMockData = async () => {
		console.log('runing')
		let qlstore = null;
		let qsAns = []
		let ql = []
		let qlClone = []
		let subjectName = '仿真考试'
		let paper = null
		let test = null
		let paperlist = null
		let sortMap = {
			2: [],
			0: [],
			1: []
		}
		let index = 0

		const testRoleInfo = await db
			.collection("test-role")
			.where({
				type_drive_id: drive,
				type_subject_id: subject,
			})
			.limit(1)
			.get();
		if (testRoleInfo.data.length > 0) {
			const _role = testRoleInfo.data[0];
			const roleItem = await db
				.collection("role-item")
				.where({
					_id: db.command.in(_role.role_item_ids),
				})
				.get();
			let q_type = {
				radio: 0,
				multiple: 1,
				judge: 2,
			};

			for (let s of roleItem.data) {
				let tempdata = await db
					.collection("test-paper")
					.where({
						s_id: cmd.eq(s.test_paper_id),
					})
					.field({
						_id: true,
						name: true,
						quesction_list: true,
						s_id: true,
					})
					.limit(1)
					.get();

				for (let r of ["radio", "multiple", "judge"]) {
					if (s[r] > 0) {
						const dt = await db
							.collection("quesction")
							.aggregate()
							.match({
								s_id: cmd.in(tempdata.data[0].quesction_list),
								q_type: cmd.eq(q_type[r]),
							})
							.sample({
								size: s[r],
							})
							.limit(s[r])
							.end();

						for (let sq of dt.data) {
							sq.infoname = subjectName;
							if (sq.q_type != 2) {
								sq.q_struct = shuffle(sq.q_struct);
								sq.realProps = resort(sq.q_struct, sq.q_ans);
							}
							sq.check = [false, false, false, false, false, false];
							ql.push(sq);
							sortMap[sq.q_type].push(index);
							index++;
						}
					}
				}
			}

			for (let j of sortMap[2]) {
				qlClone.push(ql[j]);
			}
			for (let j of sortMap[0]) {
				qlClone.push(ql[j]);
			}
			for (let j of sortMap[1]) {
				qlClone.push(ql[j]);
			}
		}
		return qlClone
	};

	const getLastHistory = async (uid) => {
		const data = await db.collection('test-history').where({user_id:uid}).limit(1).get()
		return data 
	}

	switch (ACTION) {
		case ACTION_SET.GET_MOCKTEST_DATA:
			result = await getMockData();
			break;
		case ACTION_SET.GET_LAST_HISTORY:
			result = await getLastHistory(event.uid)
			break
		case ACTION_SET.TEST:
			result = 'test';
			break
		default:
			break;
	}

	//返回数据给客户端
	return {
		code: 1,
		data: result,
		errMsg: ''
	};
};
